// import { Button, Dropdown, Menu} from 'antd';
import { GetMenuTree } from '@/services/system/menu';
import {
  addRole,
  delRole,
  GetPermissionById,
  GetRoleByPage,
  saveMenus,
  updateRole,
} from '@/services/system/role';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, notification } from 'antd';
import {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormCascader,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import { ProCard } from '@ant-design/pro-components';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
const LAYOUT_TYPE_HORIZONTAL = 'horizontal';
const Role: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['0-0-0', '0-0-1']);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['null']);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit2, setModalVisit2] = useState(false); // 绑定权限的弹框
  const [rowData, setRowData] = useState({ id: '' }); // 保存行值

  const [menuIds, setMenuIds] = useState<React.Key[]>([]); // 保存行值
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建角色'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [treeData, setTreeData] = useState([{ title: '菜单树', key: '0-0', children: [] }]); //保存菜单数据的数据
  const [responsive, setResponsive] = useState(false);
  const [saveMenuLoading, setSaveMenuLoading] = useState(false);
  const [grid, setGrid] = useState(true);
  const [formLayoutType, setFormLayoutType] = useState<FormLayout>(LAYOUT_TYPE_HORIZONTAL);
  const [form] = Form.useForm();
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '角色编号', //表头显示的名称
      dataIndex: 'code', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 180,

      align: 'center',
      sorter: true,
    },
    {
      title: '名称', //表头显示的名称
      dataIndex: 'name', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      align: 'center',
      sorter: true,
    },
    {
      title: '描述', //表头显示的名称
      search: false,
      dataIndex: 'description', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '创建日期', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createTime',
    // },
    // {
    //   title: '创建人', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createName',
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={(e) => {
            // console.log(record, '----测试----');
            // 编辑用户
            e.stopPropagation(); //阻止点击事件冒泡
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑角色');
            form.setFieldsValue({
              name: record.name,
              code: record.code,
              description: record.description,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={(e) => {
            // setRowData(record);
            // actionRef.current.reload();
            // setDeleteVisit(true);
            e.stopPropagation(); //阻止点击事件冒泡
            Modal.confirm({
              title: '删除角色',
              content: '确定要删除角色吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delRole({ id: record.id });
                actionRef.current.reload();
              },
            });
            // actionRef.current.reload();
          }}
        >
          删除
        </a>,
        // <a
        //   key="linkPermission"
        //   onClick={async (e) => {
        //     e.stopPropagation(); //阻止点击事件冒泡
        //     setModalVisit2(true); // 显示角色弹框
        //     setRowData(record);
        //     const result = await GetPermissionById({ id: record.id });
        //     setCheckedKeys(result.data);
        //     // setTreeData(result.data);
        //     // setDeleteVisit(true);
        //     // actionRef.current.reload();
        //   }}
        // >
        //   绑定权限
        // </a>,
      ],
    },
  ];
  useEffect(() => {
    // Using an IIFE
    (async () => {
      const result = await GetMenuTree();
      setTreeData(result.data);
    })();
  }, []);
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建角色') {
      const result = await addRole(form.getFieldsValue());
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateRole(form.getFieldsValue());
    }
    setConfirmLoading(false);
    setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const handleSubmit2 = async () => {
    // await addRole(form.getFieldsValue());
    setConfirmLoading2(true);
    await saveMenus({ roleId: rowData.id, menuIds: menuIds });
    // message.success('绑定关系');
    setConfirmLoading2(false);
    setModalVisit2(false);
    // 这个爆红不用管(从新加载页面)
    // actionRef.current.reload();
  };

  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(true);
  };

  const onCheck = (checkedKeysValue: React.Key[], e: any) => {
    console.log('onCheck', checkedKeysValue);
    console.log('halfCheckedKeys====', e.halfCheckedKeys);
    setMenuIds([...checkedKeysValue, ...e.halfCheckedKeys]);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', selectedKeysValue);
    setSelectedKeys(selectedKeysValue);
    // actionRef.current.reload();
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProCard split={responsive ? 'horizontal' : 'vertical'} bordered>
        <ProCard colSpan={responsive ? 24 : 20}>
          <ProTable //表格Pro组件
            headerTitle="角色查询" //表头
            actionRef={actionRef} //用于触发刷新操作等，看api
            revalidateOnFocus={false}
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            onRow={(record, index) => {
              return {
                // 点击行事件
                onClick: async (a) => {
                  a.stopPropagation();
                  console.log(record, '---record---');
                  let s = a.target.parentNode.parentNode.childNodes;
                  // 先重置为默认样式
                  for (var i = 0; i < s.length; i++) {
                    s[i].style.color = '#000000d9';
                    s[i].style.fontWeight = 'normal';
                  }
                  // 再设置高亮样式
                  a.target.parentNode.style.color = '#13C2C2';
                  a.target.parentNode.style.fontWeight = 'bold';

                  const result = await GetPermissionById({ id: record.id });
                  setCheckedKeys(result.data);
                  setRowData(record);
                },

                onDoubleClick: (a) => {
                  a.stopPropagation();
                  let s = a.target.parentNode.parentNode.childNodes;
                  // 先重置为默认样式
                  for (var i = 0; i < s.length; i++) {
                    s[i].style.color = '#000000d9';
                    s[i].style.fontWeight = 'normal';
                  }
                  // setCheckedKeys([]);
                },
              };
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  // console.log(selectedRows, '---选取多行----');
                  // 1.清空form
                  setCreateOrUpdate(false);
                  setFormTitle('新建角色');
                  form.resetFields();
                  //
                  setModalVisit(true);
                }}
                type="primary"
              >
                新建角色
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const result = await GetRoleByPage({ ...params, sorters: sorters, filters: filters });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
              // return  await new Promise({data:[{loginName:}], total:10, success: 0})
              // return {data:[], total:10, success: 0}
            }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
            columns={columns} //上面定义的
            rowSelection={{}}
            scroll={{ x: 1000, y: 300 }}
          />
        </ProCard>
        <ProCard
          colSpan={responsive ? 24 : 4}
          title={rowData?.name}
          extra={[
            <Button
              htmlType="button"
              type="primary"
              loading={saveMenuLoading}
              key="1"
              onClick={async () => {
                console.log(rowData);

                if (rowData?.id !== '') {
                  setSaveMenuLoading(true);
                  await saveMenus({ roleId: rowData.id, menuIds: menuIds });
                  message.success('保存成功！');
                  setSaveMenuLoading(false);
                } else {
                  notification.error({
                    description: '请点击角色之后再进行菜单管理',
                    message: '警告',
                  });
                }
              }}
            >
              保存
            </Button>,
          ]}
        >
          <Tree
            checkable
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            onSelect={onSelect}
            selectedKeys={selectedKeys}
            treeData={treeData}
          />
        </ProCard>
      </ProCard>

      <ModalForm
        title={formTitle}
        visible={modalVisit}
        onFinish={handleSubmit}
        modalProps={{
          onCancel: () => {
            setModalVisit(false);
          },
        }}
        layout={formLayoutType}
        grid={grid}
        rowProps={{
          gutter: [16, formLayoutType === 'inline' ? 16 : 0],
        }}
        form={form}
        // confirmLoading={confirmLoading}
        // onCancel={() => setModalVisit(false)}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />

        <ProFormText
          name="code"
          label="角色编号"
          colProps={{ md: 12, xl: 12 }}
          rules={[{ required: true, message: 'Please input your code!' }]}
        />

        <ProFormText
          name="name"
          label="名称"
          colProps={{ md: 12, xl: 12 }}
          rules={[{ required: true, message: 'Please input your name!' }]}
        />

        <ProFormText name="description" label="描述" colProps={{ md: 12, xl: 12 }} />
      </ModalForm>

      <Modal
        title={'添加角色和权限关系'}
        visible={modalVisit2}
        confirmLoading={confirmLoading2}
        onOk={handleSubmit2}
        onCancel={() => setModalVisit2(false)}
      >
        <Tree
          checkable
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          selectedKeys={selectedKeys}
          treeData={treeData}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default Role;
